package com.ruoyi.web.controller.exam.service;

import cn.hutool.core.collection.CollUtil;
import com.egdk.api.entity.*;
import com.egdk.api.mapp.ElPaperMapper;
import com.egdk.api.mapp.ElPaperQuMapper;
import com.egdk.api.mapp.ElUserBookMapper;
import com.egdk.api.mapp.ElUserExamMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SnowflakeIdWorker;
import com.ruoyi.exam.domain.PQuestion;
import com.ruoyi.exam.mapper.PExamMapper;
import com.ruoyi.exam.mapper.PQuestionMapper;
import com.ruoyi.quartz.job.enums.JobGroup;
import com.ruoyi.quartz.job.enums.JobPrefix;
import com.ruoyi.quartz.job.service.JobService;
import com.ruoyi.web.controller.exam.dto.PaperQuDTO;
import com.ruoyi.web.controller.exam.enums.PaperState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class ElPaperService {

    @Autowired
    private ElPaperMapper elPaperMapper;
    @Autowired
    private PExamMapper examMapper;
    @Autowired
    private JobService jobService;
    @Autowired
    private ElUserExamMapper userExamMapper;
    @Autowired
    private ElUserBookMapper userBookMapper;
    @Autowired
    private ElPaperQuMapper  paperQuMapper;
    @Autowired
    private PQuestionMapper questionMapper;
    private final SnowflakeIdWorker idWorker = new SnowflakeIdWorker(1, 1);



    @Transactional(rollbackFor = Exception.class)
    public void handExam(String paperId) {

        //获取试卷信息
        ElPaper paper = elPaperMapper.selectByPrimaryKey(paperId);

        //如果不是正常的，抛出异常
        if (!PaperState.ING.equals(paper.getState())) {
            throw new ServiceException("试卷状态不正确！");
        }

        // 客观分
        int objScore = elPaperMapper.sumObjective(paperId);

        paper.setObjScore(objScore);
        paper.setUserScore(objScore);

        // 主观分，因为要阅卷，所以给0
        paper.setSubjScore(0);

        // 待阅卷
        // 同步保存考试成绩
        joinResult(paper.getUserId(), paper.getExamId(), objScore, objScore >= paper.getQualifyScore());
        paper.setState(PaperState.FINISHED);
        paper.setUpdateTime(new Date());

        //计算考试时长
        Calendar cl = Calendar.getInstance();
        cl.setTimeInMillis(System.currentTimeMillis());
        int userTime = (int) ((System.currentTimeMillis() - paper.getCreateTime().getTime()) / 1000 / 60);
        if (userTime == 0) {
            userTime = 1;
        }
        paper.setUserTime(userTime);

        //更新试卷
        elPaperMapper.updateByPrimaryKeySelective(paper);


        // 终止定时任务
        String name = JobPrefix.BREAK_EXAM + paperId;
        jobService.deleteJob(name, JobGroup.SYSTEM);

        //把打错的问题加入错题本
        List<ElPaperQu> list = listByPaper(paperId);
        for (ElPaperQu qu : list) {
            // 主观题和对的都不加入错题库
            if (qu.getIsRight()) {
                continue;
            }
            //加入错题本
            new Thread(() -> addBook(paper.getExamId(), qu.getQuId())).run();
        }
    }

    private void addBook(String examId, String quId) {

        ElUserBookExample example=new ElUserBookExample();
        example.createCriteria().andExamIdEqualTo(examId).andUserIdEqualTo(SecurityUtils.getUserId()+"").andQuIdEqualTo(quId);
        //查找已有的错题信息
        List<ElUserBook> books = userBookMapper.selectByExample(example);
        // 问题
        PQuestion qu = questionMapper.selectPQuestionById(Long.valueOf(quId));
        if (CollUtil.isEmpty(books)) {
            ElUserBook book = new ElUserBook();
            book.setExamId(examId);
            book.setUserId(SecurityUtils.getUserId()+"");
            book.setTitle(qu.getQuContent());
            book.setQuId(quId);
            book.setWrongCount(1);
            book.setId(idWorker.nextId() + "");
            Integer maxSort = this.findMaxSort(examId, SecurityUtils.getUserId()+"");
            book.setSort(maxSort+1);
            userBookMapper.insertSelective(book);
        } else {
            ElUserBook book=books.get(0);
            book.setWrongCount(book.getWrongCount()+1);
            userBookMapper.updateByPrimaryKeySelective(book);
        }
    }

    private Integer findMaxSort(String examId, String userId) {
        ElUserBookExample example=new ElUserBookExample();
        example.createCriteria().andExamIdEqualTo(examId).andUserIdEqualTo(userId);
        example.setOrderByClause("sort DESC");
        List<ElUserBook> books=userBookMapper.selectByExample(example);
        if(CollUtil.isEmpty(books)){
            return 0;
        }
        return books.get(0).getSort();
    }

    private List<ElPaperQu> listByPaper(String paperId) {
        //查询条件
        ElPaperQuExample example=new ElPaperQuExample();
        example.createCriteria().andPaperIdEqualTo(paperId);

        List<ElPaperQu> records = paperQuMapper.selectByExample(example);

        return records;
    }


    public void joinResult(String userId, String examId, Integer score, boolean passed) {

        //查询条件

        ElUserExamExample example=new ElUserExamExample();
        example.createCriteria().andUserIdEqualTo(userId).andExamIdEqualTo(examId);

        List<ElUserExam> records = userExamMapper.selectByExample(example);
        if (CollUtil.isEmpty(records)) {
            ElUserExam record = new ElUserExam();
            record.setCreateTime(new Date());
            record.setUpdateTime(new Date());
            record.setUserId(userId);
            record.setExamId(examId);
            record.setMaxScore(score);
            record.setPassed(passed);
            record.setId(idWorker.nextId() + "");
            userExamMapper.insertSelective(record);
            return;
        }
        ElUserExam record=records.get(0);
        // 修复低分数不加入统计问题
        record.setTryCount(record.getTryCount() + 1);
        record.setUpdateTime(new Date());

        if (record.getMaxScore() < score) {
            record.setMaxScore(score);
            record.setPassed(passed);
        }

        userExamMapper.updateByPrimaryKeySelective(record);
    }


}
